package com.jh.user.service;

import java.math.BigDecimal;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.jh.user.business.UserBalanceBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.business.UserRebateHistoryBusiness;
import com.jh.user.business.UserRoleResourceBusiness;
import com.jh.user.pojo.UserAccount;
import com.jh.user.pojo.UserRebateHistory;
import com.jh.user.util.Util;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.TokenUtil;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class UserRebateService {

	private static final Logger LOG = LoggerFactory.getLogger(UserRebateService.class);

	@Autowired
	private UserRebateHistoryBusiness userRebateHistoryBusiness;


	@Autowired
	private UserLoginRegisterBusiness  userLoginRegisterBusiness;


	@Autowired
	private UserRoleResourceBusiness userRoleResourceBusiness;


	@Autowired
	private UserBalanceBusiness userBalBusiness;

	@Autowired
	Util util;

	/**更新用户的分润信息 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/rebate/update")
	public @ResponseBody Object updateUserAccount(HttpServletRequest request,
												  @RequestParam(value = "user_id") long userId,
												  @RequestParam(value = "rebate_amount",  defaultValue = "0") BigDecimal rebateamount,
												  @RequestParam(value = "order_code") String orderCode,
												  @RequestParam(value = "addorsub",  defaultValue = "0") String addorsub,
												  @RequestParam(value = "order_type",  defaultValue = "0") String order_type
	){

		Map<String,Object> map = new HashMap<String,Object>();
		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userId);

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userRebateHistoryBusiness.updateUserRebate(userAccount, rebateamount, order_type,  addorsub, orderCode));
		String realname="";
		long lower_userid=0;
		{
			/**获取订单信息*/
			URI uri = util.getServiceUrl("transactionclear", "error url request!");
			String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
			MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
			requestEntity.add("order_code", orderCode);
			RestTemplate restTemplate=new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			JSONObject jsonObject =  JSONObject.fromObject(result);
			JSONObject authObject  =  jsonObject.getJSONObject("result");
			if(jsonObject.containsKey("result")){
				lower_userid=authObject.getLong("userid");
			}
		}
		{
			/* 获取身份证实名信息*/
			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
			String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
			MultiValueMap<String, Long> requestEntity  = new LinkedMultiValueMap<String, Long>();
			requestEntity.add("userid", lower_userid);
			RestTemplate restTemplate=new RestTemplate();
			String result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================/v1.0/paymentchannel/realname/userid" + result);
			JSONObject jsonObject =  JSONObject.fromObject(result);
			JSONObject authObject  =  jsonObject.getJSONObject("realname");
			if(authObject!=null){
				if(authObject.getString("result")!=null&&authObject.getString("result").equals("1")){
					String real_name=(authObject.getString("realname")==null||authObject.getString("realname").equals("null")?"":authObject.getString("realname"));
					realname=real_name.substring(0,1)+"**";
				}

			}
		}

		return map;

	}


	/**查询交易变更历史*/
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/rebate/query/{token}")
	public @ResponseBody Object pageBalanceQuery(HttpServletRequest request,
												 @PathVariable("token") String token,
												 @RequestParam(value = "page", defaultValue = "0", required = false) int page,
												 @RequestParam(value = "size", defaultValue = "20", required = false) int size,
												 @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
												 @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty
	){

		Map<String,Object> map = new HashMap<String,Object>();
		long userId;
		try{
			userId = TokenUtil.getUserId(token);
		}catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		if(page <0){
			page = 0;
		}
		Pageable pageable = new PageRequest(page, size, new Sort(direction,sortProperty));

		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT, userRebateHistoryBusiness.queryUserRebateHistoryByUserid(userId, pageable));
		return map;
	}
	/**统计收益
	 * 当天、昨天、当月、当年、所有
	 * */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/rebate/query/sumrebate")
	public @ResponseBody Object pageBalanceQuery(HttpServletRequest request,
												 @RequestParam(value = "user_id") long  userId,
												 @RequestParam(value = "end_time",  required = false) String  endTime,
												 @RequestParam(value = "start_time",  required = false) String startTime,
												 @RequestParam(value = "order_type", defaultValue = "1,0", required = false) String orderType
	){
		Map<String,Object> sumMap = new HashMap<String,Object>();
		String[] orderTypeA = orderType.split(",");
		{//当天
			Date startTimeDate = null;
			if(startTime != null  && !startTime.equalsIgnoreCase("")){
				startTimeDate = DateUtil.getDateFromStr(startTime);
			}else{
				startTime=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				startTimeDate = DateUtil.getDateFromStr(startTime);
			}
			Date endTimeDate=null;
			Calendar   calendar   =   new   GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate=calendar.getTime();   //这个时间就是日期往后推一天的结果
			BigDecimal sumRebate=userRebateHistoryBusiness.findsumRebateHistoryByUseridAnd(userId, orderTypeA, startTimeDate, endTimeDate);
			sumMap.put("todayRebate",sumRebate!=null?sumRebate.setScale(2, BigDecimal.ROUND_DOWN):"0.00");
		}
		{//昨天
			Date startTimeDate = null;
			if(startTime != null  && !startTime.equalsIgnoreCase("")){
				startTimeDate = DateUtil.getDateFromStr(startTime);
			}else{
				startTime=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
				startTimeDate = DateUtil.getDateFromStr(startTime);
			}
			Date endTimeDate=null;
			Calendar   calendar   =   new   GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
			startTimeDate=calendar.getTime();   //这个时间就是日期往后推一天的结果
			calendar   =   new   GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate=calendar.getTime();   //这个时间就是日期往后推一天的结果
			BigDecimal sumRebate=userRebateHistoryBusiness.findsumRebateHistoryByUseridAnd(userId, orderTypeA, startTimeDate, endTimeDate);
			sumMap.put("yesterdayRebate",sumRebate!=null?sumRebate.setScale(2, BigDecimal.ROUND_DOWN):"0.00" );
		}
		{ //当月
			Date startTimeDate = null;
			if(startTime != null  && !startTime.equalsIgnoreCase("")){
				startTime=new SimpleDateFormat("yyyy-MM").format(DateUtil.getDateFromStr(startTime));
				startTimeDate = getYYMMDateFromStr(startTime);
			}else{
				startTime=new SimpleDateFormat("yyyy-MM").format(new Date());
				startTimeDate =getYYMMDateFromStr(startTime);
			}
			Date endTimeDate=null;
			Calendar   calendar   =   new   GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.MONTH,1);//把日期往后增加一天.整数往后推,负数往前移动
			endTimeDate=calendar.getTime();   //这个时间就是日期往后推一天的结果
			BigDecimal sumRebate=userRebateHistoryBusiness.findsumRebateHistoryByUseridAnd(userId, orderTypeA, startTimeDate, endTimeDate);
			sumMap.put("monthRebate", sumRebate!=null?sumRebate.setScale(2, BigDecimal.ROUND_DOWN):"0.00");
		}
		{//所有
			Date startTimeDate = DateUtil.getDateFromStr("2017-05-01");
			Date endTimeDate=new Date();
			BigDecimal sumRebate=userRebateHistoryBusiness.findsumRebateHistoryByUseridAnd(userId, orderTypeA, startTimeDate, endTimeDate);
			sumMap.put("allRebate",sumRebate!=null?sumRebate.setScale(2, BigDecimal.ROUND_DOWN):"0.00");
		}
		Map<String,Object> map = new HashMap<String,Object>();
		LOG.info("查询分润统计："+sumMap);
		map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		map.put(CommonConstants.RESULT,sumMap );
		return map;
	}
	/**统计收益
	 * 上月
	 * */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/rebate/query/sumrebatepremonth")
	public @ResponseBody Object pageBalanceQueryLastMonth(HttpServletRequest request,
														  @RequestParam(value = "user_id") long  userId,
														  @RequestParam(value = "end_time",  required = false) String  endTime,
														  @RequestParam(value = "start_time",  required = false) String startTime,
														  @RequestParam(value = "order_type", defaultValue = "1,0", required = false) String orderType
	){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> sumMap = new HashMap<String,Object>();
		try {
			String[] orderTypeA = orderType.split(",");
			Date startTimeDate = null;
			if(startTime != null  && !startTime.equalsIgnoreCase("")){
				startTime=new SimpleDateFormat("yyyy-MM").format(DateUtil.getDateFromStr(startTime));
				startTimeDate = getYYMMDateFromStr(startTime);
			}else{
				startTime=new SimpleDateFormat("yyyy-MM").format(new Date());
				startTimeDate =getYYMMDateFromStr(startTime);
			}
			Date endTimeDate=null;
			Calendar   calendar   =   new   GregorianCalendar();
			calendar.setTime(startTimeDate);
			calendar.add(calendar.MONTH,-1);//把日期往后增加一天.整数往后推,负数往前移动 
			endTimeDate=calendar.getTime();   //这个时间就是日期往后推一天的结果 
			BigDecimal sumRebate=userRebateHistoryBusiness.findsumRebateHistoryByUseridAnd(userId, orderTypeA, endTimeDate,startTimeDate );
			if(null==sumRebate) {
				map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "上月没有收益");
			}else {
				sumMap.put("monthRebate", sumRebate!=null?sumRebate.setScale(2, BigDecimal.ROUND_DOWN):"0.00");
				LOG.info("查询分润统计："+sumMap);
				map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT,sumMap );
			}

		}catch(Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, e.getMessage());
		}
		return map;
	}
	public static Date getYYMMDateFromStr(String str){

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Date result = null;
		try {
			result =  sdf.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}
	@RequestMapping(method = RequestMethod.POST,value="/v1.0/user/rebate/query/oneweek/{token}")
	public @ResponseBody Object getOneWeekRebate(HttpServletRequest request,
												 @PathVariable(value="token")String token
	){
		Map<String,Object>map = new HashMap<>();
		Map<String,Object>sumRebateMap = new HashMap<>();
		Map<String,Object>returnSumRebateMap = new HashMap<>();
		long userId;
		try{
			userId = TokenUtil.getUserId(token);
		}catch (Exception e) {
			map.put(CommonConstants.RESP_CODE,CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar =  new GregorianCalendar();
		calendar.add(Calendar.DATE, -6);
		Date startDate = calendar.getTime();
		Date endDate = new Date();
		List<Object[]> models =  userRebateHistoryBusiness.findSumRebateHistoryByUserIdBetweenWeek(userId, new String[]{"0","1"},sdf.format(startDate),sdf.format(endDate));
		if(models!=null&&models.size()>0){
			for(int i = 0;i < models.size();i++){
				sumRebateMap.put(models.get(i)[0]+"", models.get(i)[1]);
			}
			if(!sumRebateMap.isEmpty()){
				for(int i = 0;i < 7;i++){
					calendar =  new GregorianCalendar();
					calendar.add(Calendar.DATE, -i);
					Object value = sumRebateMap.get(sdf.format(calendar.getTime()));
					returnSumRebateMap.put(i+"", value==null||"".equals(value)?0:value);
				}
			}else{
				for(int i = 0;i < 7;i++){
					returnSumRebateMap.put(i+"", 0);
				}
			}
		}else{
			for(int i = 0;i < 7;i++){
				returnSumRebateMap.put(i+"", 0);
			}
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, returnSumRebateMap);
		return map;
	}
}
